package com.jiang.demo.controller;

import com.jiang.demo.common.MSGException;
import com.jiang.demo.common.MSG;
import com.jiang.demo.view.vo.EnumVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Api(tags = "api公共接口")
@RestController
@RequestMapping("/api/common")
public class CommonController {

    @GetMapping("/enum")
    @ApiOperation("根据全类名获取枚举数据项")
    @ApiImplicitParam(name = "className", required = true, dataType = "string", value ="全类名")
    public MSG<List<EnumVO>> getEnums(@RequestParam("className") String className) throws Exception {
        Class<?> cls;
        try {
            cls = Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw MSGException.DATA_ERROR;
        }
        Object[] enumConstants = cls.getEnumConstants();
        List<EnumVO> list = new ArrayList<>();
        for (Object en : enumConstants) {
            Class<?> enClass = en.getClass();
            Method getValue = enClass.getMethod("getValue");    // 需要与枚举类方法对应
            Method getDesc = enClass.getMethod("getDesc");      // 需要与枚举类方法对应
            list.add(new EnumVO((Integer) getValue.invoke(en), (String) getDesc.invoke(en)));
        }
        return MSG.SUCCESS(list);
    }
}
